var im = require('../../utils/im.js')
var util = require('../../utils/util.js')
import cache from '../../utils/cache.js'
// var userInfo = wx.getStorageSync('userInfo')
/**
 * 在线客服，在用户信息里面，需要在会话列表里面过滤掉
 */

var msgType = {
  'p2p-0001': '交易消息',
  'p2p-0000': '系统通知'
}
/**
 * 获取个人的订单，
 */
var tempSessions = []
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imInstance:null,
    endTime: 0,
    startTime: 0,
    sesstionList: [],
    csList: [],
    notifyList: [],
    orderNotifyList: [],
    cssesstion:null
  },
  decorateList (sesstionList) { // 展示到页面最后的装饰，主要用来修改格式
    sesstionList.forEach((item) => {
      item.updateTime = util.formatTime(item.updateTime)
    })
    // 未读数量进行排序
    if (sesstionList.unread != undefined) {
      sesstionList.sort(function(a, b) {
        return a.unread < b.unread
      })
    }
  },
  sortOrderList (list) {
    // 更新时间进行排序
    list.sort(function(a, b) {
      return a.updateTime < b.updateTime
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  initEvent(){
    // 客服列表更新
    wx.eventBus.on('update_csList', (options) => {
      wx.setStorageSync("message-csList", options.csList)
      wx.eventBus.trigger('get_csList')
    })
    wx.eventBus.on('get_csList', (options) => {
      var csList = wx.getStorageSync('message-csList') || []
      this.decorateList(csList)
      console.log('csList', csList)
      this.setData({
        csList: csList
      })
    })
    // 完全更新
    wx.eventBus.on('total_update_sesstionlist', (options) => {
      console.log('options', options);
      this.filterSession(options.sesstionList)
    })
    //会话列表
    wx.eventBus.on('update_sesstionlist', (options) => {
      wx.setStorageSync("message-sesstionList", options.sesstionList)
      wx.eventBus.trigger('get_sesstionlist')
    })
    wx.eventBus.on('get_sesstionlist', (options) => {
      var sesstionList = wx.getStorageSync('message-sesstionList') || []
      this.decorateList(sesstionList)
      console.log('会话列表', sesstionList);
      this.setData({
        sesstionList: sesstionList
      })
    })
    //通知列表
    wx.eventBus.on('update_orderNotifyList', (options) => {
      wx.setStorageSync("message-orderNotifyList", options.data)
      wx.eventBus.trigger('get_orderNotifyList')
    })
    wx.eventBus.on('get_orderNotifyList', (options) => {
      var orderNotifyList = wx.getStorageSync('message-orderNotifyList') || []
      this.decorateList(orderNotifyList)
      console.log('刷新后的交易信息', orderNotifyList)
      this.setData({
        orderNotifyList: orderNotifyList
      })
    })
  },
  filterSession (sesstion) { // 更新
    if (!sesstion) return
    // 过滤已结束的会话
    var teamList = cache.get('_team_list');
    sesstion = sesstion.filter(it => {
      if (it.scene == 'p2p') return it;
      let matchItem = teamList.filter(i => {
        return it.to == i.teamId
      })[0];
      let obj = null;
      if (matchItem && matchItem.serverCustom) {
        obj = JSON.parse(matchItem.serverCustom);
      }
      if (matchItem && matchItem.clientCustom) {
        obj = JSON.parse(matchItem.clientCustom);
      }
      if (obj && obj.state != 1) { // 1 为无效群
        return it
      } else {
        console.log('无效群+1')
      }
    })
    console.log('过滤无效群后的消息',sesstion);
    var orderNotifyList = [] // 交易信息
    var sesstionList = [] // 单、群聊天集合
    var p2pList = [] // 单聊集合
    var teamList = [] // 群聊集合
    var csList = [] // 在线客服
    var systemNoticeList = [] // 系统通知
    sesstion.forEach((item) => {
      if (item.id == 'p2p-0001') {
        orderNotifyList.push(item)
      } else if (item.id == 'p2p-0000') {
        systemNoticeList.push(item)
      } else {
        if (item.scene == 'team') { // 群聊找患者信息
          if (item.to == this.userInfo.server_room) { // 过滤在线客服
            csList.push(item)
          } else {
             var temp = cache.get('_team_list').filter(el => {
              return el.teamId == item.to
            })
            if (temp.length > 0) {
              var cs = temp[0].serverCustom || temp[0].custom
            }
            try  {
              item.serverCustom = JSON.parse(cs)
           } catch (e) {
              console.log('cs', cs)
           }
            item.avatar = '../../resource/icon/default/order-img.png';
            if (item.serverCustom && item.serverCustom.state != '1') {
              teamList.push(item);
            }
          }
        } else if (item.scene == 'p2p') { // 单聊找对方信息
          p2pList.push(item)
        }
      }
    })
    if (p2pList.length > 0) {
      var accountArr = p2pList.map(el => {
        return el.to
      })
      wx.nim.getUsers({
        accounts: accountArr,
        done: function(error, users) {
          console.log('users', users)
          console.log('p2pList', p2pList)
          p2pList.forEach((el, idx) => {
            el.userInfo = users[idx]
            el.avatar = users[idx].avatar
          })
          cache.set('_p2p_userInfo_list', p2pList)
          cache.set('_team_patientInfo_list',teamList)
          sesstionList = teamList.concat(p2pList)
          wx.eventBus.trigger('update_csList', { "csList": csList })
          wx.eventBus.trigger('update_sesstionlist', { "sesstionList": sesstionList })
          wx.eventBus.trigger('update_orderNotifyList', { "data": orderNotifyList })
        }
      })
    } else {
      cache.set('_p2p_userInfo_list', p2pList)
      cache.set('_team_patientInfo_list',teamList)
      sesstionList = teamList.concat(p2pList)
      wx.eventBus.trigger('update_csList', { "csList": csList })
      wx.eventBus.trigger('update_sesstionlist', { "sesstionList": sesstionList })
      wx.eventBus.trigger('update_orderNotifyList', { "data": orderNotifyList })
    }
  },
  onLoad: function (options) {
    this.userInfo = wx.getStorageSync('userInfo');
    this.initEvent();
    // if (cache.get('_current_ss')) {
    //   this.filterSession(cache.get('_current_ss'))
    // }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // console.log('页面显示')
    var appUserInfo = this.userInfo;
    console.log('还会执行吗?')
    if (appUserInfo && appUserInfo.accid) { // 用户已经存在
       if (!cache.get('_team_list')) {
        console.log('链接..')
        wx.showLoading({
          title: '正在连接IM……',
          mask: true
        });
        this.imInstance = im.setOptions({
          account: appUserInfo.accid,
          token: appUserInfo.token,
          onsessions: (ss) => {
            console.log('收到消息推送',ss);
            cache.set('_current_ss', ss);
            wx.hideLoading();
            this.filterSession(ss);
          }
        }).getInstance()
      } else { // 刷新操作
        console.log('刷新后的```');
        var ss = cache.get('_current_ss'); // 仅仅是聊天会话更新;
        console.log('所有消息会话', ss)
        this.filterSession(ss);
      }
    } else {
      console.log('用户不存在')
    }

    cache.set('currentSessionId', null) // 在此页时候重置当前会话id
    // wx.eventBus.on('receive_msg', (params) => { // 文本
    //   console.log('params', params)
    // })
    // wx.eventBus.on('receive_img', (params) => { // 图片
    // })
    // wx.eventBus.on('receive_file', (params) => { // 文件
    // })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  // onPullDownRefresh: function () {

  // },

  /**
   * 页面上拉触底事件的处理函数
   */
  // onReachBottom: function () {

  // },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  },
  /**
   * 跳转到stl页面
   */
  pushHtml: function () {
    var url_path = escape('https://testadmin.1sju.com/yishuju-viewstl/?orderId=21537&type=operation');
    var url = '../home/homehtml/homehtml?url_path=' + url_path + '&title=' + 'stl预览' + '&isescape=' + '1';
    wx.navigateTo({
      url: url
    })
  },
  notify: function (e) {
    let insApp = getApp();
    if (!insApp.loginQuery(true)) return
    let info = e.currentTarget.dataset.info
    var sessionId
    console.log('info', info)
    if (info.length > 0) {
      sessionId = info[0].lastMsg.sessionId
    }
    wx.navigateTo({
      url: './notify/notify?sessionId=' + sessionId
    })
  },
  deleteSesstion: function (e) {
    console.log(e.currentTarget.dataset.item)
    this.imInstance.deleteSession({
      scene: e.currentTarget.dataset.item.scene,
      to: e.currentTarget.dataset.item.to,
      done: deleteSessionDone
    });
    function deleteSessionDone(error, obj) {

      console.log(error);
      console.log(obj);
      console.log('删除服务器上的会话' + (!error ? '成功' : '失败'));
    }
  },
  toChat: function (e) { // 跳转到会话
    let id = e.currentTarget.dataset.id
    let info = e.currentTarget.dataset.info
    console.log('info', info)
    if (info.scene == 'team') { // 群聊带teamId
      let teamId = info.to
      wx.navigateTo({
        url: './chat/chat?id=' + id + '&teamId=' + teamId
      })
    }
    if (info.scene == 'p2p') { // 单聊带uid
      let uid = info.userInfo.account
      wx.navigateTo({
        url: './chat/chat?id=' + id + '&uid=' + uid + '&to=' + info.to
      })
    }
    console.log('id', id)

  },
  onlineService: function () { // 跳转到在线客服
    let insApp = getApp();
    if (!insApp.loginQuery(true)) return
      wx.navigateTo({
        url: './chat/chat' // 不带id为客服
      })
  },
  onTabItemTap (item) {
    console.log('点击了消息页的导航栏')
    return
  }
})